//
//  ZJComposePictureView.swift
//  Webo
//
//  Created by 曾静 on 16/7/3.
//  Copyright © 2016年 qq. All rights reserved.
//

import UIKit

private let cellId = "cellId"
class ZJComposePictureView: UICollectionView {

    var imageList:[UIImage] = [UIImage]()
    
    var clourse:(()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        self.delegate = self
        
        self.dataSource = self
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        
        //首次设置视图的 时候隐藏配图 
        hidden = true
        
        self.backgroundColor = UIColor.whiteColor()
        
        //注册
        self.registerClass(ZJComposePictureViewCell.self, forCellWithReuseIdentifier: cellId)
        
        let layout = collectionViewLayout as!UICollectionViewFlowLayout
        
        
        let itemMargin: CGFloat = 5
        
        let  itemWH = (SCREENW - 2 * itemMargin - 2 * OriginalMargin)/3
        
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        layout.minimumInteritemSpacing = itemMargin
        
        layout.minimumLineSpacing = itemMargin
        
    }
    
    func addImages(image:UIImage){
        
        //在数组的第一个元素的位置添加一个元素
        self.imageList.insert(image, atIndex: 0)
        
        //设置这句话最多上传8张图片
        if imageList.count > 8{
            self.imageList.removeLast()
        }
        
        hidden = false
        
        //添加完元素之后记得刷新UI
        reloadData()
    }
    
    
}
extension ZJComposePictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath)as!ZJComposePictureViewCell
        
        
        //如果有给nil didset时候就会加号按钮
        
        
        if imageList.count == indexPath.row{
            
            cell.image = nil
            
            
        }else{
            
             cell.image = self.imageList[indexPath.row]
        }
        
        //每个按钮对应一个indexPath无需加参数
        cell.cellClourse = {
            
            
            //删除指定元素的数组
            self.imageList.removeAtIndex(indexPath.item)
            
            if self.imageList.count == 0{
                
                self.hidden = true
            }
            
            self.reloadData()
        }
       

        return cell
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if imageList.count == 0 || imageList.count == 9 {
            
            return imageList.count
            
        }else{
            
            return imageList.count + 1
        }
    }
  
   
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        collectionView.deselectItemAtIndexPath(indexPath, animated: false)
        //如果点击的是加号按钮
        if imageList.count == indexPath.row{
            
            
            clourse?()
            
        }
        
        
    }
    
}
class ZJComposePictureViewCell: UICollectionViewCell{
    
    
    var cellClourse:(()->())?
    //定义一个属性,用来设自己的item,在
    var image:UIImage?{
        
        
        didSet{
            //如果有值直接赋值,这就是使用可选值的好处
            if image == nil{
                
                //加号图片
                itemImageView.image = UIImage(named: "compose_pic_add")
                
                itemImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                
//               cencelBtn.setBackgroundImage(nil, forState: UIControlState.Normal)
                //考虑到服用的问题我们设置隐藏
                cencelBtn.hidden = true
                
            }else{
                
                //加号图片
                itemImageView.image = image
                
                itemImageView.highlightedImage = image
                
                 cencelBtn.hidden = false
                
            }
            
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: -  设置视图
    private func setupUI(){
        
        //添加控件
        contentView.addSubview(itemImageView)

        contentView.addSubview(cencelBtn)
        //添加约束
        itemImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        cencelBtn.snp_makeConstraints { (make) -> Void in
            
            make.trailing.top.equalTo(contentView)
        }
    }
    
    func cancelBtnClick(){
        
        //按钮点击之后就会告诉外面的控制器更改图片数组的个数,使用闭包的形式
        cellClourse?()
        
    }
    
    //懒加载控件
    private lazy var itemImageView:UIImageView = UIImageView()

    //懒加载删除按钮
    private lazy var cencelBtn:UIButton = {
      
         let btn =  UIButton()
        
        btn.addTarget(self, action: "cancelBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        return btn
    
    }()
 
}